import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

export default function Vip() {
  const navigate = useNavigate();
  const [checked, setChecked] = useState(false);
  const [selected, setSelected] = useState(0); // 0:包月, 1:包年, 2:12个月
  const [showPayModal, setShowPayModal] = useState(false);

  // 浅蓝色主色
  const mainBlue = '#4FC3F7';
  const lightBlue = '#B3E5FC';
  const borderBlue = '#81D4FA';

  // 套餐数据
  const plans = [
    {
      name: '连续包月',
      tag: '新用户专享价',
      price: 1,
      oldPrice: 18,
      save: 17,
      label: 'SVIP',
      gradient: `linear-gradient(135deg, ${mainBlue} 60%, ${borderBlue} 100%)`,
      border: `1.5px solid ${mainBlue}`,
      tagBg: mainBlue,
      tagColor: '#111',
      labelBg: '#fff2',
      labelColor: '#fff',
      saveBg: mainBlue,
      saveColor: '#fff',
      textColor: '#fff',
    },
    {
      name: '连续包年',
      tag: '低至7.4元/月',
      price: 88,
      oldPrice: 216,
      save: 128,
      label: 'SVIP',
      gradient: '#f5f5f5',
      border: `1.5px solid ${borderBlue}`,
      tagBg: '#eee',
      tagColor: mainBlue,
      labelBg: '#eee',
      labelColor: mainBlue,
      saveBg: '#eee',
      saveColor: mainBlue,
      textColor: '#111',
    },
    {
      name: '12个月',
      tag: '',
      price: 172,
      oldPrice: 216,
      save: 44,
      label: '',
      gradient: '#f5f5f5',
      border: `1.5px solid ${borderBlue}`,
      tagBg: '',
      tagColor: '',
      labelBg: '',
      labelColor: '',
      saveBg: '',
      saveColor: '',
      textColor: '#111',
    },
  ];

  // 按钮文字和价格随套餐变化
  const btnText = `${plans[selected].price}元开通`;

  // 按钮点击事件
  const handleOpen = () => {
    setShowPayModal(true);
  };

  // 支付方式点击
  const handlePay = async (type: string) => {
    if (type === '微信') {
      // 直接激活VIP，弹窗不消失
      const userName = localStorage.getItem('userName');
      let expreDate = '';
      const now = new Date();
      if (plans[selected].price === 1) {
        expreDate = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()).toISOString().split('T')[0];
      } else {
        expreDate = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate()).toISOString().split('T')[0];
      }
      try {
        const response = await fetch('/hongbao-lzt/activate-vip', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ userName, expireDate: expreDate })
        });
        if (response.ok) {
          // 支付成功，但弹窗不消失，页面不跳转
          console.log('微信支付成功，用户状态已更新为VIP');
        } else {
          console.error('微信支付失败');
        }
      } catch (error) {
        console.error('微信支付请求失败:', error);
      }
          } else if (type === '支付宝') {
        // 支付宝支付时关闭弹窗
        setShowPayModal(false);
        try {
          // 支付前保存套餐信息到localStorage，userId用userName
          const userName = localStorage.getItem('userName') || 'user_' + Date.now();
          localStorage.setItem('userId', userName);
          localStorage.setItem('planType', plans[selected].name);
          localStorage.setItem('expireDate', getExpireDate(plans[selected].name));
          const orderId = 'order_' + Date.now();
          const res = await fetch('/sha-lzt/pay', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              ooder: orderId, // 参数名与后端一致
              money: plans[selected].price,
              subject: plans[selected].name,
            })
          });
          const data = await res.text();
          // 创建一个div插入form并自动提交
          const div = document.createElement('div');
          div.innerHTML = data;
          document.body.appendChild(div);
          const form = div.querySelector('form');
          if (form) {
            form.submit();
          } else {
            alert('未找到支付表单，支付跳转失败');
          }
        } catch (e) {
          alert('请求支付接口失败');
        }
      } else {
        // 其他支付方式也关闭弹窗
        setShowPayModal(false);
        alert(type + '支付暂未开通');
      }
  };

  // 根据套餐类型计算到期时间
  const getExpireDate = (planType: string) => {
    const now = new Date();
    switch (planType) {
      case '连续包月':
        return new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()).toISOString().split('T')[0];
      case '连续包年':
        return new Date(now.getFullYear() + 1, now.getMonth(), now.getDate()).toISOString().split('T')[0];
      case '12个月':
        return new Date(now.getFullYear() + 1, now.getMonth(), now.getDate()).toISOString().split('T')[0];
      default:
        return new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()).toISOString().split('T')[0];
    }
  };

  return (
    <div style={{ minHeight: '100vh', background: '#fff', color: '#111', fontFamily: 'PingFang SC, Arial', paddingBottom: 16 }}>
      {/* 顶部栏 */}
      <div style={{ display: 'flex', alignItems: 'center', height: 44, padding: '0 10px' }}>
        <div style={{ cursor: 'pointer', marginRight: 6 }} onClick={() => navigate(-1)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M15 19L8 12L15 5" stroke="#111" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <div style={{ fontWeight: 700, fontSize: 17, flex: 1 }}>成为会员</div>
      </div>
      {/* 副标题 */}
      <div style={{ color: '#888', fontSize: 12, marginLeft: 16, marginBottom: 4 }}>尊享高品质会员服务</div>
      {/* 套餐选择区 */}
      <div style={{ display: 'flex', gap: 8, justifyContent: 'center', margin: '12px 0 0 0', flexWrap: 'wrap' }}>
        {plans.map((plan, idx) => {
          const isSelected = selected === idx;
          const bg = isSelected
            ? `linear-gradient(135deg, ${mainBlue} 60%, ${borderBlue} 100%)`
            : '#f5f5f5';
          const textColor = isSelected ? '#fff' : '#111';
          return (
            <div
              key={plan.name}
              style={{
                background: bg,
                borderRadius: 10,
                padding: '10px 10px 8px 10px',
                minWidth: 80,
                boxShadow: `0 1px 6px ${mainBlue}22`,
                color: textColor,
                position: 'relative',
                flex: 1,
                maxWidth: 110,
                border: isSelected ? `1.5px solid ${mainBlue}` : `1.5px solid ${borderBlue}`,
                outline: isSelected ? `2.5px solid ${mainBlue}` : 'none',
                cursor: 'pointer',
                transition: 'outline 0.2s, background 0.2s, color 0.2s',
              }}
              onClick={() => setSelected(idx)}
            >
              {plan.tag && (
                <div style={{ position: 'absolute', top: 6, left: 6, background: isSelected ? mainBlue : '#eee', color: isSelected ? '#111' : mainBlue, fontWeight: 700, fontSize: 10, borderRadius: 6, padding: '1px 5px' }}>{plan.tag}</div>
              )}
              <div style={{ fontWeight: 700, fontSize: 13, marginTop: plan.tag ? 18 : 10 }}>
                {plan.name}
                {plan.label && (
                  <span style={{ fontSize: 10, background: isSelected ? '#fff2' : '#eee', color: isSelected ? '#fff' : mainBlue, borderRadius: 4, padding: '1px 4px', marginLeft: 2 }}>{plan.label}</span>
                )}
              </div>
              <div style={{ fontSize: 18, fontWeight: 900, margin: '4px 0 1px 0' }}>￥{plan.price}</div>
              <div style={{ color: isSelected ? '#eee' : '#aaa', fontSize: 10, textDecoration: 'line-through' }}>￥{plan.oldPrice}</div>
              {plan.save > 0 && (
                <div style={{ color: isSelected ? '#fff' : mainBlue, background: isSelected ? mainBlue : '#eee', borderRadius: 6, fontSize: 10, marginTop: 4, padding: '1px 5px', display: 'inline-block', border: isSelected ? 'none' : `1px solid ${mainBlue}` }}>立省{plan.save}元</div>
              )}
            </div>
          );
        })}
      </div>
      {/* SVIP特权 */}
      <div style={{ margin: '18px 0 0 0', padding: '0 12px' }}>
        <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 8, color: '#111' }}>SVIP特权</div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, minWidth: 60 }}>
            <div style={{ background: lightBlue, borderRadius: 8, padding: 5, marginBottom: 2 }}>
              <svg width="18" height="18" viewBox="0 0 28 28"><rect x="4" y="8" width="20" height="12" rx="4" fill={mainBlue}/><text x="14" y="20" textAnchor="middle" fill="#fff" fontSize="9">AD</text></svg>
            </div>
            <div style={{ fontSize: 10, color: '#888' }}>尊贵红色昵称</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, minWidth: 60 }}>
            <div style={{ background: lightBlue, borderRadius: 8, padding: 5, marginBottom: 2 }}>
              <svg width="18" height="18" viewBox="0 0 28 28"><rect x="4" y="8" width="20" height="12" rx="4" fill={mainBlue}/><text x="14" y="20" textAnchor="middle" fill="#fff" fontSize="9">惠</text></svg>
            </div>
            <div style={{ fontSize: 10, color: '#888' }}>全商品9折</div>
          </div>
        </div>
      </div>
      {/* 常见问题 */}
      <div style={{ margin: '18px 0 0 0', padding: '0 12px' }}>
        <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 6, color: '#111' }}>常见问题</div>
        <div style={{ background: '#f5f5f5', borderRadius: 6, padding: '7px 10px', color: '#888', fontSize: 11, marginBottom: 5 }}>会员开通后是否支持退款？<br/>答：不支持退款，请确认后再购买。</div>
        <div style={{ background: '#f5f5f5', borderRadius: 6, padding: '7px 10px', color: '#888', fontSize: 11 }}>会员权益是否可转让？<br/>答：不可转让，仅限本人使用。</div>
      </div>
      {/* 协议勾选与开通按钮 */}
      <div style={{ margin: '18px 12px 0 12px', background: 'none' }}>
        <label style={{ display: 'flex', alignItems: 'center', fontSize: 11, color: '#888', marginBottom: 6 }}>
          <input type="checkbox" checked={checked} onChange={e => setChecked(e.target.checked)} style={{ marginRight: 5 }} />
          已阅读并同意《会员自动续费服务协议》，不支持退款
        </label>
        <div>
          <button
            disabled={!checked}
            style={{
              width: '100%', background: checked ? mainBlue : '#eee', color: checked ? '#111' : '#aaa', border: 'none', borderRadius: 8, padding: '8px 0', fontWeight: 700, fontSize: 15, cursor: checked ? 'pointer' : 'not-allowed', marginBottom: 6
            }}
            onClick={checked ? handleOpen : undefined}
          >
            {btnText}
          </button>
        </div>
      </div>
      {/* 支付方式弹框 */}
      {showPayModal && (
        <div style={{
          position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: 'rgba(0,0,0,0.25)', zIndex: 9999,
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }} onClick={() => setShowPayModal(false)}>
          <div style={{ background: '#fff', borderRadius: 14, minWidth: 260, padding: '24px 18px 18px 18px', boxShadow: '0 2px 16px #0002', textAlign: 'center', position: 'relative' }} onClick={e => e.stopPropagation()}>
            <div style={{ fontWeight: 700, fontSize: 17, color: '#111', marginBottom: 18 }}>选择支付方式</div>
            <button style={{ width: '100%', background: '#09bb07', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 0', fontWeight: 700, fontSize: 16, marginBottom: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }} onClick={() => handlePay('微信')}> 
              <svg width="22" height="22" viewBox="0 0 48 48"><circle cx="24" cy="24" r="24" fill="#09bb07"/><path d="M16 28c-2.21 0-4-1.79-4-4s1.79-4 4-4m16 8c2.21 0 4-1.79 4-4s-1.79-4-4-4m-8 12c-6.63 0-12-4.03-12-9s5.37-9 12-9 12 4.03 12 9-5.37 9-12 9z" fill="#fff"/></svg>
              微信支付
            </button>
            <button style={{ width: '100%', background: '#00A0E9', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 0', fontWeight: 700, fontSize: 16, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }} onClick={() => handlePay('支付宝')}>
              <svg width="22" height="22" viewBox="0 0 48 48"><circle cx="24" cy="24" r="24" fill="#00A0E9"/><text x="24" y="30" textAnchor="middle" fill="#fff" fontSize="18">支</text></svg>
              支付宝支付
            </button>
            <button style={{ position: 'absolute', top: 8, right: 10, background: 'none', border: 'none', color: '#888', fontSize: 20, cursor: 'pointer' }} onClick={() => setShowPayModal(false)}>&times;</button>
          </div>
        </div>
      )}
    </div>
  );
}
